import React, { useState, useEffect } from 'react';
import './PropsDemo.css';

// 1. 基础 Props 传递和读取
const UserCard = (props) => {
  return (
    <div className="user-card">
      <h3>{props.name}</h3>
      <p>年龄: {props.age}</p>
      <p>职业: {props.occupation}</p>
      <p>邮箱: {props.email}</p>
    </div>
  );
};

// 2. 使用解构赋值读取 props
const ProductCard = ({ name, price, description, image, onBuy }) => {
  return (
    <div className="product-card">
      <img src={image} alt={name} className="product-image" />
      <h3>{name}</h3>
      <p className="price">¥{price}</p>
      <p className="description">{description}</p>
      <button onClick={onBuy} className="buy-btn">
        购买
      </button>
    </div>
  );
};

// 3. 为 props 指定默认值
const Button = ({ 
  text = '点击我', 
  type = 'primary', 
  size = 'medium',
  disabled = false,
  onClick 
}) => {
  return (
    <button 
      className={`btn btn-${type} btn-${size}`}
      disabled={disabled}
      onClick={onClick}
    >
      {text}
    </button>
  );
};

// 4. 传递 JSX 作为 props
const Card = ({ title, children, footer }) => {
  return (
    <div className="card">
      <div className="card-header">
        <h2>{title}</h2>
      </div>
      <div className="card-body">
        {children} {/* 这里渲染传递的 JSX */}
      </div>
      {footer && (
        <div className="card-footer">
          {footer}
        </div>
      )}
    </div>
  );
};

// 5. 传递函数作为 props
const Counter = ({ initialValue = 0, onCountChange }) => {
  const [count, setCount] = useState(initialValue);

  const increment = () => {
    const newCount = count + 1;
    setCount(newCount);
    onCountChange && onCountChange(newCount);
  };

  const decrement = () => {
    const newCount = count - 1;
    setCount(newCount);
    onCountChange && onCountChange(newCount);
  };

  return (
    <div className="counter">
      <h3>计数器: {count}</h3>
      <div className="counter-controls">
        <Button text="减少" onClick={decrement} type="secondary" />
        <Button text="增加" onClick={increment} type="primary" />
      </div>
    </div>
  );
};

// 6. 传递对象和数组作为 props
const DataTable = ({ data, columns, onRowClick }) => {
  return (
    <div className="data-table">
      <table>
        <thead>
          <tr>
            {columns.map((column, index) => (
              <th key={index}>{column.title}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map((row, rowIndex) => (
            <tr 
              key={rowIndex} 
              onClick={() => onRowClick && onRowClick(row)}
              className="table-row"
            >
              {columns.map((column, colIndex) => (
                <td key={colIndex}>{row[column.key]}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

// 7. 条件渲染和 props 验证
const ConditionalComponent = ({ show, content, fallback }) => {
  if (!show) {
    return fallback || <div>内容不可用</div>;
  }
  
  return <div className="conditional-content">{content}</div>;
};

// 主演示组件
const PropsDemo = () => {
  const [currentTime, setCurrentTime] = useState(new Date());
  const [selectedUser, setSelectedUser] = useState(null);
  const [counterValue, setCounterValue] = useState(0);

  // 模拟时间变化
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  // 用户数据
  const users = [
    { id: 1, name: '张三', age: 25, occupation: '前端工程师', email: 'zhangsan@example.com' },
    { id: 2, name: '李四', age: 30, occupation: '产品经理', email: 'lisi@example.com' },
    { id: 3, name: '王五', age: 28, occupation: 'UI设计师', email: 'wangwu@example.com' }
  ];

  // 产品数据
  const products = [
    {
      id: 1,
      name: 'React 实战教程',
      price: 99,
      description: '从入门到精通的 React 学习指南',
      image: 'https://via.placeholder.com/150x100?text=React'
    },
    {
      id: 2,
      name: 'Vue.js 开发手册',
      price: 88,
      description: 'Vue.js 3.0 完整开发指南',
      image: 'https://via.placeholder.com/150x100?text=Vue'
    }
  ];

  // 表格数据
  const tableData = [
    { id: 1, name: '项目A', status: '进行中', progress: '75%' },
    { id: 2, name: '项目B', status: '已完成', progress: '100%' },
    { id: 3, name: '项目C', status: '待开始', progress: '0%' }
  ];

  const tableColumns = [
    { key: 'id', title: 'ID' },
    { key: 'name', title: '项目名称' },
    { key: 'status', title: '状态' },
    { key: 'progress', title: '进度' }
  ];

  const handleBuy = (product) => {
    alert(`购买了: ${product.name}`);
  };

  const handleRowClick = (row) => {
    setSelectedUser(row);
  };

  const handleCountChange = (newCount) => {
    setCounterValue(newCount);
  };

  return (
    <div className="props-demo">
      <h2>🎯 React Props 深度解析</h2>
      
      <div className="demo-section">
        <h3>1. 基础 Props 传递和读取</h3>
        <div className="user-cards">
          {users.map(user => (
            <UserCard
              key={user.id}
              name={user.name}
              age={user.age}
              occupation={user.occupation}
              email={user.email}
            />
          ))}
        </div>
      </div>

      <div className="demo-section">
        <h3>2. 解构赋值读取 Props</h3>
        <div className="product-cards">
          {products.map(product => (
            <ProductCard
              key={product.id}
              {...product} // 展开运算符传递所有属性
              onBuy={() => handleBuy(product)}
            />
          ))}
        </div>
      </div>

      <div className="demo-section">
        <h3>3. Props 默认值</h3>
        <div className="button-demo">
          <Button text="主要按钮" type="primary" />
          <Button text="次要按钮" type="secondary" />
          <Button text="小按钮" size="small" />
          <Button text="大按钮" size="large" />
          <Button text="禁用按钮" disabled={true} />
          <Button /> {/* 使用所有默认值 */}
        </div>
      </div>

      <div className="demo-section">
        <h3>4. 传递 JSX 作为 Props</h3>
        <div className="card-demo">
          <Card 
            title="用户信息卡片"
            footer={<Button text="保存" type="primary" />}
          >
            <p>这是通过 children 传递的内容</p>
            <p>可以包含任何 JSX 元素</p>
            <ul>
              <li>列表项 1</li>
              <li>列表项 2</li>
              <li>列表项 3</li>
            </ul>
          </Card>

          <Card title="简单卡片">
            <p>这个卡片没有 footer</p>
          </Card>
        </div>
      </div>

      <div className="demo-section">
        <h3>5. 传递函数作为 Props</h3>
        <div className="counter-demo">
          <Counter 
            initialValue={10} 
            onCountChange={handleCountChange}
          />
          <p>父组件接收到的计数: {counterValue}</p>
        </div>
      </div>

      <div className="demo-section">
        <h3>6. 传递对象和数组</h3>
        <DataTable 
          data={tableData}
          columns={tableColumns}
          onRowClick={handleRowClick}
        />
        {selectedUser && (
          <div className="selected-user">
            <h4>选中的项目: {selectedUser.name}</h4>
            <p>状态: {selectedUser.status}</p>
            <p>进度: {selectedUser.progress}</p>
          </div>
        )}
      </div>

      <div className="demo-section">
        <h3>7. 条件渲染和 Props 验证</h3>
        <div className="conditional-demo">
          <ConditionalComponent 
            show={true}
            content={<p>这是显示的内容</p>}
          />
          
          <ConditionalComponent 
            show={false}
            fallback={<p>这是自定义的备用内容</p>}
          />
        </div>
      </div>

      <div className="demo-section">
        <h3>8. Props 随时间变化</h3>
        <div className="time-demo">
          <p>当前时间: {currentTime.toLocaleTimeString()}</p>
          <p>当前日期: {currentTime.toLocaleDateString()}</p>
          <p>时间戳: {currentTime.getTime()}</p>
        </div>
      </div>

      <div className="demo-section">
        <h3>9. Props 传递的最佳实践</h3>
        <div className="best-practices">
          <div className="practice-item">
            <h4>✅ 使用解构赋值</h4>
                         <code>{'const MyComponent = ({ prop1, prop2 }) => { ... }'}</code>
          </div>
          
          <div className="practice-item">
            <h4>✅ 设置默认值</h4>
                         <code>{'const MyComponent = ({ prop = defaultValue }) => { ... }'}</code>
          </div>
          
          <div className="practice-item">
            <h4>✅ 传递函数时使用 useCallback</h4>
                         <code>{'const handleClick = useCallback(() => { ... }, [deps])'}</code>
          </div>
          
          <div className="practice-item">
            <h4>✅ 使用 PropTypes 或 TypeScript</h4>
                         <code>{'MyComponent.propTypes = { prop: PropTypes.string }'}</code>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PropsDemo; 